#include <stdio.h>
#include <string>

using std::string;

string reverseWords(string s) {
    if (s == "") return "";
    // remove redundant space
    int i = 0, j = 0;
    int l = s.size();
    int l2 = 0;
    bool headspace = 1;
    for (; i < l; ++i) {
        if (s[i] == ' ') {
            // strip left spaces
            if (headspace) {
                continue;
            } else { // leave only 1 space
                if (s[i-1] == ' ') {
                    continue;
                }
            }
        }
        headspace = false;
        s[j] = s[i];
        ++j;
    }
    // strip right space
    if (s[j-1] == ' ') {
        l2 = --j;
    } else {
        l2 = j;
    }
    // reverse the whole string
    for (i = 0; i < l2/2; ++i) {
        char t = s[i];
        s[i] = s[l2-i-1];
        s[l2-i-1] = t;
    }
    // reverse each word when 1.meet ' '; 2.reach the end
    int wordstart = 0;
    for (i = 0; i < l2; ++i) {
        if (i == l2 - 1 || s[i] == ' ') {
            if (i == l2 - 1) i++;
            for (j = wordstart; j < (i-wordstart)/2+wordstart; ++j) {
                char t = s[j];
                s[j] = s[i-(j-wordstart)-1];
                s[i-(j-wordstart)-1] = t;
            }
            wordstart = i+1;
        }
    }
    return s.substr(0, l2);
}

int main() {
    string s = "  the  good   example    "; // "example good a"
    printf("Ori: '%s'\nResult: '%s'\n", s.c_str(), reverseWords(s).c_str());
}
